<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="springboot-step-by-step,">










<meta name="description" content="本文为《一步一步学习Spring Boot 2》的第十一章的学习笔记，主要内容为SpringBoot集成消息队列与异步调用 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta name="keywords" content="springboot-step-by-step">
<meta property="og:type" content="article">
<meta property="og:title" content="【第十一章】一步一步学习SpringBoot2——集成消息队列与异步调用">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/07/20/spring-boot-step-by-step-six/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为《一步一步学习Spring Boot 2》的第十一章的学习笔记，主要内容为SpringBoot集成消息队列与异步调用 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726092525367.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726092809769.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726095746903.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726103700924.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726103801047.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726112450677.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726113127372.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726114214509.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726114311034.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726114350969.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726114445416.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726120510695.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726120601131.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726140936581.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190726141333229.jpg">
<meta property="og:updated_time" content="2019-07-26T06:15:07.305Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第十一章】一步一步学习SpringBoot2——集成消息队列与异步调用">
<meta name="twitter:description" content="本文为《一步一步学习Spring Boot 2》的第十一章的学习笔记，主要内容为SpringBoot集成消息队列与异步调用 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190726092525367.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/07/20/spring-boot-step-by-step-six/">





  <title>【第十一章】一步一步学习SpringBoot2——集成消息队列与异步调用 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/07/20/spring-boot-step-by-step-six/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第十一章】一步一步学习SpringBoot2——集成消息队列与异步调用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-20T09:24:24+08:00">
                2019-07-20
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Springboot/" itemprop="url" rel="index">
                    <span itemprop="name">Springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为《一步一步学习Spring Boot 2》的第十一章的学习笔记，主要内容为SpringBoot集成消息队列与异步调用</p>
<p>本书博客地址：<a href="https://blog.csdn.net/huangwenyi1010?t=1" target="_blank" rel="noopener">https://blog.csdn.net/huangwenyi1010?t=1</a></p>
<p>源代码地址：<a href="https://gitee.com/aiolos123/springboot-step-by-step" target="_blank" rel="noopener">https://gitee.com/aiolos123/springboot-step-by-step</a></p>
<a id="more"></a>

<h1 id="JMS消息服务简介"><a href="#JMS消息服务简介" class="headerlink" title="JMS消息服务简介"></a>JMS消息服务简介</h1><blockquote>
<p>JMS：（Java Message Service，即Java消息服务），是一组Java应用程序接口，提供了消息的创建、发送、读取等一系列服务的接口与语法。类似于JDBC，是一种与具体厂商无关的API。 使得Java程序能够与不同厂商的消息组件很好地进行通信。</p>
</blockquote>
<h2 id="JMS的两种消息发送接收模型"><a href="#JMS的两种消息发送接收模型" class="headerlink" title="JMS的两种消息发送接收模型"></a>JMS的两种消息发送接收模型</h2><blockquote>
<p>JMS支持两种消息发送和接收模型：P2P(Ponit to Point)模型、Pub/Sub(Publish/Subscribe，即发布-订阅)模型</p>
</blockquote>
<ol>
<li><p>P2P模式图如下图所示：<br><img src="/blog/images/20190726092525367.jpg" alt="P2P模式图"></p>
</li>
<li><p>Pub/Sub模式图如下图所示：<br><img src="/blog/images/20190726092809769.jpg" alt="Pub/Sub模式图"></p>
</li>
<li><p>两种模型的区别与联系见下表</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>模型名称</th>
<th>本质区别</th>
<th>模型含义</th>
<th>特点</th>
</tr>
</thead>
<tbody><tr>
<td>P2P(Ponit to Point)点对点模型</td>
<td>一对一广播(每个消息只有一个消费者 (即一旦被消费，消息就不在消息队列中))；通过中介队列传递消息</td>
<td>P2P模型采用点对点的方式发送消息。P2P模型是基于队列的，消息生产者（Producer/Sender）发送消息到队列，消息消费者（Consumer/Receiver）从队列中接收消息，队列的存在使得消息的异步传输成为可能。P2P模式图如上</td>
<td>1. <strong>每个消息只有一个消费者 (即一旦被消费，消息就不在消息队列中)</strong>; 2. 发送者和接收者之间在时间上没有依赖性，也就是说当发送者发送了消息之后，不管接收者有没有正在运行，它不会影响消息被发送到队列中；3. 接收者在成功接收消息之后需向队列应答成功</td>
</tr>
<tr>
<td>Pub/Sub (Publish/Subscribe)发布订阅模型</td>
<td>一对多广播(每个消息可以有多个消费者)；通过中介Topic传递消息；</td>
<td>发布-订阅模型定义了如何向一个内容节点( 称为 Topic（主题）)发布和订阅消息。主题可以认为是消息传递的中介，消息发布者将消息发布到某个主题，而消息订阅者则从主题订阅消息。主题使得消息的订阅者与消息的发布者互相保持独立，不需要进行接触即可保证消息的传递，发布-订阅模型在消息的一对多广播时采用。Pub/Sub模式图如上</td>
<td>1. <strong>每个消息可以有多个消费者</strong>；2. 发布者和订阅者之间有时间上的依赖性。针对某个主题（Topic）的订阅者，它必须创建一个订阅者之后，才能消费发布者的消息，而且为了消费消息，订阅者必须保持运行的状态。为了缓和这样严格的时间相关性，JMS允许订阅者创建一个可持久化的订阅。这样，即使订阅者没有被激活（运行），它也能接收到发布者的消息。</td>
</tr>
</tbody></table>
<ol start="4">
<li>如果你希望发送的消息可以不做任何处理、或者被一个消息者处理、或者可以被多个消费者处理的话，那么可以采用Pub/Sub模型</li>
</ol>
<h1 id="SpringBoot集成消息队列"><a href="#SpringBoot集成消息队列" class="headerlink" title="SpringBoot集成消息队列"></a>SpringBoot集成消息队列</h1><h2 id="ActiveMQ安装"><a href="#ActiveMQ安装" class="headerlink" title="ActiveMQ安装"></a>ActiveMQ安装</h2><blockquote>
<p>MQ英文名MessageQueue(消息队列)，是一个消息的接受和转发的容器，可用于消息推送。</p>
</blockquote>
<blockquote>
<p>ActiveMQ是Apache提供的一个开源的消息系统，完全采用Java来实现，因此，它能很好地支持J2EE提出的JMS（Java Message Service,即Java消息服务）规范。</p>
</blockquote>
<ol>
<li>下载<br>ActiveMQ官网下载地址：<a href="http://activemq.apache.org/activemq-5150-release.html" target="_blank" rel="noopener">http://activemq.apache.org/activemq-5150-release.html</a></li>
</ol>
<p><img src="/blog/images/20190726095746903.jpg" alt="Pub/Sub模式图"></p>
<p>将官网下载的安装包apache-activemq-5.15.0-bin.zip解压。</p>
<ol start="2">
<li>启动ActiveMQ</li>
</ol>
<p>打开解压的文件夹，进入bin目录，根据电脑操作系统是32位还是64位，选择进入【win32】文件夹或者【win64】文件夹。<br>双击【activemq.bat】，即可启动ActiveMQ<br>当看到如下图所示的启动信息时，代表ActiveMQ启动成功。从图中可以看出，ActiveMQ默认启动到8161端口。<br><img src="/blog/images/20190726103700924.jpg" alt="ActiveMQ启动成功"></p>
<ol start="3">
<li>安装成功之后，我们在浏览器中输入<a href="http://localhost:8161/admin链接访问，第一次访问需要输入用户名admin和密码admin进行登录，登录成功之后，我们就可以看到ActiveMQ的首页。具体如下图所示。" target="_blank" rel="noopener">http://localhost:8161/admin链接访问，第一次访问需要输入用户名admin和密码admin进行登录，登录成功之后，我们就可以看到ActiveMQ的首页。具体如下图所示。</a><br><img src="/blog/images/20190726103801047.jpg" alt="ActiveMQ启动成功"></li>
</ol>
<h2 id="SpringBoot集成ActiveMQ"><a href="#SpringBoot集成ActiveMQ" class="headerlink" title="SpringBoot集成ActiveMQ"></a>SpringBoot集成ActiveMQ</h2><h3 id="引入依赖"><a href="#引入依赖" class="headerlink" title="引入依赖"></a>引入依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Spring Boot集成ActiveMQ--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-activemq<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="添加配置"><a href="#添加配置" class="headerlink" title="添加配置"></a>添加配置</h3><p>在application.properties配置文件中添加ActiveMQ配置</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">###ActiveMQ配置################################</span><br><span class="line">spring.activemq.broker-url=tcp:<span class="comment">//127.0.0.1:61616</span></span><br><span class="line">spring.activemq.<span class="keyword">in</span>-memory=true</span><br><span class="line">spring.activemq.pool.enabled=false</span><br><span class="line">spring.activemq.packages.trust-all=true</span><br></pre></td></tr></table></figure>

<p>说明：<br>spring.activemq.packages.trust-all：ObjectMessage的使用机制是不安全的，ActiveMQ自5.12.2和5.13.0之后，强制Consumer端声明一份可信任的包列表，只有当ObjectMessage中的Object在可信任包内，才能被提取出来。该配置表示信任所有的包。</p>
<h2 id="未使用ActiveMQ的开发说说功能"><a href="#未使用ActiveMQ的开发说说功能" class="headerlink" title="未使用ActiveMQ的开发说说功能"></a>未使用ActiveMQ的开发说说功能</h2><ol>
<li><p>首先在数据库中建立说说表ay_mood<br><img src="/blog/images/20190726112450677.jpg" alt="建立说说表ay_mood"></p>
</li>
<li><p>数据库表建好之后，我们生成对应的实体类AyMood</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@Entity</span></span><br><span class="line"><span class="variable">@Data</span></span><br><span class="line">public class AyMood implements Serializable &#123;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@Id</span></span><br><span class="line">    <span class="variable">@GeneratedValue</span>(strategy = GenerationType.IDENTITY)</span><br><span class="line">    private Integer id;</span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">private</span> <span class="selector-tag">String</span> <span class="selector-tag">content</span>;</span><br><span class="line">    <span class="selector-tag">private</span> <span class="selector-tag">Integer</span> <span class="selector-tag">userid</span>;</span><br><span class="line">    <span class="comment">//点赞数量</span></span><br><span class="line">    <span class="selector-tag">private</span> <span class="selector-tag">Integer</span> <span class="selector-tag">praisenum</span>;</span><br><span class="line">    <span class="comment">//发表时间</span></span><br><span class="line">    <span class="selector-tag">private</span> <span class="selector-tag">Date</span> <span class="selector-tag">publishtime</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>AyMood实体对象开发完成之后，我们开发对应的AyMoodRepository接口</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">public<span class="built_in"> interface </span>AyMoodRepository extends JpaRepository&lt;AyMood,Integer&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Repository接口开发完成之后，我们开发对应的说说服务层接口AyMoodService和相应的实现类AyMoodServiceImpl</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IAyMoodService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function">AyMood <span class="title">save</span><span class="params">(AyMood ayMood)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyMoodServiceImpl</span> <span class="keyword">implements</span> <span class="title">IAyMoodService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> AyMoodRepository ayMoodRepository;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 在实现类AyMoodServiceImpl中，我们注入AyMoodRepository接口，</span></span><br><span class="line"><span class="comment">     * 并调用其提供的save() 方法，保存说说到数据库。</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ayMood</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AyMood <span class="title">save</span><span class="params">(AyMood ayMood)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ayMoodRepository.save(ayMood);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>单元测试</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Resource</span></span><br><span class="line"><span class="keyword">private</span> AyMoodService ayMoodService;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">void</span> <span class="title">testAyMood</span><span class="params">()</span></span>&#123;</span><br><span class="line">    AyMood ayMood = <span class="keyword">new</span> AyMood();</span><br><span class="line">    ayMood.setId(<span class="string">"1"</span>);</span><br><span class="line">    <span class="comment">//用户阿毅id为1</span></span><br><span class="line">    ayMood.setUserId(<span class="string">"1"</span>);</span><br><span class="line">    ayMood.setPraiseNum(<span class="number">0</span>);</span><br><span class="line">    <span class="comment">//说说内容</span></span><br><span class="line">    ayMood.setContent(<span class="string">"这是我的第一条微信说说！！！"</span>);</span><br><span class="line">    ayMood.setPublishTime(<span class="keyword">new</span> Date());</span><br><span class="line">    <span class="comment">//往数据库保存一条数据，代码用户阿毅发表了一条说说</span></span><br><span class="line">    AyMood mood = ayMoodService.save(ayMood);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行代码后，数据库中新增一条记录<br><img src="/blog/images/20190726113127372.jpg" alt="单元测试"></p>
<h3 id="引出的问题"><a href="#引出的问题" class="headerlink" title="引出的问题"></a>引出的问题</h3><pre><code>引出的问题：大量请求的实时保存引起的服务和数据库压力</code></pre><ol>
<li>引出的问题</li>
</ol>
<blockquote>
<p>用户发表说说的类虽然都开发完成了，但是有一个问题，我们都知道微信的用户量极大，每天都有几亿的用户发表不同的说说。</p>
</blockquote>
<blockquote>
<p>如果按照我们上面的做法，<strong>用户每发一条说说，后端都会单独开一个线程，将该说说的内容实时的保存到数据库中。我们都知道后端服务系统的线程数和数据库线程池中的线程数量都是固定而且宝贵的，因此将用户发表的说说实时保存到数据库中，必然造成后端服务和数据库极大的压力</strong>。</p>
</blockquote>
<ol start="2">
<li>解决办法</li>
</ol>
<blockquote>
<p>所有我们使用ActiveMQ做异步消费，来抵抗用户大并发发表说说而产生的压力，提高系统整体的性能————不再实时保存数据到数据库中。</p>
</blockquote>
<h2 id="使用ActiveMQ的开发步骤"><a href="#使用ActiveMQ的开发步骤" class="headerlink" title="使用ActiveMQ的开发步骤"></a>使用ActiveMQ的开发步骤</h2><ol>
<li><p>开发消息的生产者<br><img src="/blog/images/20190726114214509.jpg" alt="开发消息的生产者"></p>
</li>
<li><p>开发消息的消费者<br><img src="/blog/images/20190726114311034.jpg" alt="开发消息的消费者"></p>
</li>
<li><p>单元测试<br><img src="/blog/images/20190726114350969.jpg" alt="开发消息的消费者"></p>
</li>
<li><p>浏览器访问<a href="http://localhost:8161/admin/，查看队列ay.queue的消费情况" target="_blank" rel="noopener">http://localhost:8161/admin/，查看队列ay.queue的消费情况</a><br><img src="/blog/images/20190726114445416.jpg" alt="查看队列ay.queue的消费情况"></p>
</li>
</ol>
<h1 id="使用ActiveMQ将发表说说改为异步消费模式"><a href="#使用ActiveMQ将发表说说改为异步消费模式" class="headerlink" title="使用ActiveMQ将发表说说改为异步消费模式"></a>使用ActiveMQ将发表说说改为异步消费模式</h1><p>在上一节我们把生产者和消费者开发完成之后，现在我们把用户发说说改成异步消费模式。</p>
<ol>
<li>首先在IAyMoodService接口中添加异步保存方法asynSave()，并实现该方法。该方法并不保存说说记录，而是调用AyMoodProducer类的sendMessage推送消息</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyMoodServiceImpl</span> <span class="keyword">implements</span> <span class="title">IAyMoodService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//异步保存说说的MQ队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Destination destination = <span class="keyword">new</span> ActiveMQQueue(<span class="string">"ay.queue.asyn.save"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> AyMoodProducer ayMoodProducer;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 异步保存说说</span></span><br><span class="line"><span class="comment">     * asynSave方法并不保存说说记录，而是调用AyMoodProducer类的sendMessage推送消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ayMood</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">asynSave</span><span class="params">(AyMood ayMood)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//往队列ay.queue.asyn.save中推送消息，消息内容为说说实体</span></span><br><span class="line">        ayMoodProducer.sendMessage(destination,ayMood);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>其次，在AyMoodProducer生产者类下添加sendMessage(Destination destination, final AyMood ayMood)方法，消息内容是ayMood实体对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyMoodProducer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> JmsMessagingTemplate jmsMessagingTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendMessage</span><span class="params">(Destination destination, <span class="keyword">final</span> AyMood ayMood)</span> </span>&#123;</span><br><span class="line">        jmsMessagingTemplate.convertAndSend(destination, ayMood);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>最后，修改AyMoodConsumer消费者，在receiveQueue方法中保持说说记录</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyMoodConsumer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> IAyMoodService iAyMoodService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@JmsListener</span>：使用JmsListener配置消费者监听的队列ay.queue.asyn.save</span></span><br><span class="line"><span class="comment">     * 在receiveQueue方法中保持说说记录</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ayMood</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@JmsListener</span>(destination = <span class="string">"ay.queue.asyn.save"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">receiveQueue</span><span class="params">(AyMood ayMood)</span></span>&#123;</span><br><span class="line">        iAyMoodService.save(ayMood);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>单元测试<br><img src="/blog/images/20190726120510695.jpg" alt="单元测试"></p>
</li>
<li><p>浏览器访问<a href="http://localhost:8161/admin/，查看队列ay.queue.asyn.save的消费情况" target="_blank" rel="noopener">http://localhost:8161/admin/，查看队列ay.queue.asyn.save的消费情况</a><br><img src="/blog/images/20190726120601131.jpg" alt="查看队列的消费情况"></p>
</li>
</ol>
<h1 id="SpringBoot实现异步调用"><a href="#SpringBoot实现异步调用" class="headerlink" title="SpringBoot实现异步调用"></a>SpringBoot实现异步调用</h1><blockquote>
<p>在Spring Boot框架中，只要通过@Async注解就能将普通的同步任务改为异步调用任务。</p>
</blockquote>
<h2 id="异步调用"><a href="#异步调用" class="headerlink" title="异步调用"></a>异步调用</h2><p>同步调用：是指程序按预定顺序一步步执行，每一步必须等到上一步执行完成之后才能执行。<br>异步调用：异步调用则无需等待上一步程序执行完成即可执行。</p>
<h2 id="并行的处理任务的两种方式：多线程、异步调用"><a href="#并行的处理任务的两种方式：多线程、异步调用" class="headerlink" title="并行的处理任务的两种方式：多线程、异步调用"></a>并行的处理任务的两种方式：多线程、异步调用</h2><p>在日常开发的项目中，当访问的接口较慢或者做耗时任务时，不想程序一直卡在耗时任务上，想让程序能够并行执行，我们除了可以使用多线程来并行的处理任务，也可以使用Spring Boot提供的异步处理方式@Async来处理</p>
<h2 id="Spring-Boot实现异步调用"><a href="#Spring-Boot实现异步调用" class="headerlink" title="Spring Boot实现异步调用"></a>Spring Boot实现异步调用</h2><pre><code>SpringBoot实现异步调用两大步骤：
  一. 在入口类添加注解@EnableAsync开启异步调用
  二. 通过@Async注解就能将普通的同步任务改为异步调用任务</code></pre><ol>
<li><p>在入口类添加注解@EnableAsync开启异步调用</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@SpringBootApplication</span></span><br><span class="line"><span class="variable">@EnableAsync</span> <span class="comment">//开启异步调用</span></span><br><span class="line">public class StepbystepApplication &#123;</span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">public</span> <span class="selector-tag">static</span> <span class="selector-tag">void</span> <span class="selector-tag">main</span>(String[] args) &#123;</span><br><span class="line">        <span class="selector-tag">SpringApplication</span><span class="selector-class">.run</span>(StepbystepApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改AyUserServiceImpl类的findAll方法，使它能够记录方法执行花费的时间</p>
<figure class="highlight zephir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">List</span>&lt;AyUser&gt; findAll() &#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        logger.info(<span class="string">"开始做任务"</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">List</span>&lt;AyUser&gt; ayUserList = ayUserRepository.findAll();</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        logger.info(<span class="string">"完成任务，耗时："</span> + (end - start) + <span class="string">"毫秒"</span>);</span><br><span class="line">        <span class="keyword">return</span> ayUserList;</span><br><span class="line">    &#125;<span class="keyword">catch</span> (<span class="keyword">Exception</span> e)&#123;</span><br><span class="line">        logger.error(<span class="string">"method [findAll()] error"</span>,e);</span><br><span class="line">        <span class="keyword">return</span> Collections.EMPTY_LIST;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>测试同步调用花费的时间<br><img src="/blog/images/20190726140936581.jpg" alt="测试同步调用花费的时间"></p>
</li>
</ol>
<ol start="4">
<li>在AyUserService接口中添加异步查询方法findAsynAll()，并在AyUserServiceImpl类实现该方法<blockquote>
<p>通过@Async注解将普通的同步任务改为异步调用任务</p>
</blockquote>
</li>
</ol>
<figure class="highlight zephir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 异步调用</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">@Override</span><br><span class="line">@Async</span><br><span class="line"><span class="keyword">public</span> Future&lt;<span class="keyword">List</span>&lt;AyUser&gt;&gt; findAsynAll() &#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        logger.info(<span class="string">"开始做任务"</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">List</span>&lt;AyUser&gt; ayUserList = ayUserRepository.findAll();</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        logger.info(<span class="string">"完成任务，耗时："</span> + (end - start) + <span class="string">"毫秒"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> AsyncResult&lt;<span class="keyword">List</span>&lt;AyUser&gt;&gt;(ayUserList) ;</span><br><span class="line">    &#125;<span class="keyword">catch</span> (<span class="keyword">Exception</span> e)&#123;</span><br><span class="line">        logger.error(<span class="string">"method [findAsynAll()] error"</span>,e);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> AsyncResult&lt;<span class="keyword">List</span>&lt;AyUser&gt;&gt;(<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="5">
<li>测试异步调用花费的时间<br><img src="/blog/images/20190726141333229.jpg" alt="测试同步调用花费的时间"></li>
</ol>
<p>从上面的打印结果可以看出，异步调用方法执行速度比同步调用方法快74毫秒（764-690）。由此说明异步调用的速度比同步调用快。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/springboot-step-by-step/" rel="tag"># springboot-step-by-step</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/07/19/spring-boot-step-by-step-five-two/" rel="next" title="【第十章】一步一步学习SpringBoot2——集成MyBatis与MyBatisPlus">
                <i class="fa fa-chevron-left"></i> 【第十章】一步一步学习SpringBoot2——集成MyBatis与MyBatisPlus
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/07/20/spring-boot-step-by-step-six-two/" rel="prev" title="【第十二章】一步一步学习SpringBoot2——Springboot集成MongoDB">
                【第十二章】一步一步学习SpringBoot2——Springboot集成MongoDB <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#JMS消息服务简介"><span class="nav-number">1.</span> <span class="nav-text">JMS消息服务简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JMS的两种消息发送接收模型"><span class="nav-number">1.1.</span> <span class="nav-text">JMS的两种消息发送接收模型</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SpringBoot集成消息队列"><span class="nav-number">2.</span> <span class="nav-text">SpringBoot集成消息队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ActiveMQ安装"><span class="nav-number">2.1.</span> <span class="nav-text">ActiveMQ安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringBoot集成ActiveMQ"><span class="nav-number">2.2.</span> <span class="nav-text">SpringBoot集成ActiveMQ</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#引入依赖"><span class="nav-number">2.2.1.</span> <span class="nav-text">引入依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加配置"><span class="nav-number">2.2.2.</span> <span class="nav-text">添加配置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#未使用ActiveMQ的开发说说功能"><span class="nav-number">2.3.</span> <span class="nav-text">未使用ActiveMQ的开发说说功能</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#引出的问题"><span class="nav-number">2.3.1.</span> <span class="nav-text">引出的问题</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用ActiveMQ的开发步骤"><span class="nav-number">2.4.</span> <span class="nav-text">使用ActiveMQ的开发步骤</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用ActiveMQ将发表说说改为异步消费模式"><span class="nav-number">3.</span> <span class="nav-text">使用ActiveMQ将发表说说改为异步消费模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SpringBoot实现异步调用"><span class="nav-number">4.</span> <span class="nav-text">SpringBoot实现异步调用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#异步调用"><span class="nav-number">4.1.</span> <span class="nav-text">异步调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#并行的处理任务的两种方式：多线程、异步调用"><span class="nav-number">4.2.</span> <span class="nav-text">并行的处理任务的两种方式：多线程、异步调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring-Boot实现异步调用"><span class="nav-number">4.3.</span> <span class="nav-text">Spring Boot实现异步调用</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
